<template>
    <el-card>
     <el-upload
          ref="fileUpload"
          class="upload-demo"
          drag
          :action="baseURL + other.adaptationUrl('/aigc/embedding/doc/')"
          :data="uploadData"
          :on-success="handleUploadSuccess"
          :before-upload="handleBeforeUpload"
          :on-error="handleUploadError"
          :on-remove="handleRemove"
          :on-progress="handleProgress"
          multiple
          show-file-list
        >
          <el-icon class="el-icon--upload">
                <upload-filled />
          </el-icon>
          <div class="el-upload__text">
            Drop file here or <em>click to upload</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
            {{t('aigcKnowledge.importDataFileTip')}}
            </div>
          </template>
        </el-upload>
        <el-progress v-if="showProcess"
            :percentage="processPercent"
            :status="processStatus"
            >
        </el-progress>
    </el-card>
</template>

<script setup lang="ts" name="aigcKnowledgeImport">
    import {useI18n} from "vue-i18n";
    import {useMessage} from '/@/hooks/message';
    import other from '/@/utils/other';

    const {t} = useI18n();
    //父组件传值，子组件接收props参数，并定义类型
    const props = defineProps({
      data: {
        type: Object as PropType<any>,
        default: () => ({}),
       },
      fileType: { type: Array, default: () => [] },
      fileSize: { type: Number, default: 0 },
    });
    //父组件传值，子组件接收emit事件
    const emit = defineEmits(['change', 'update:modelValue'])
    //上传参数
    const uploadData = ref({
        knowledgeId: props.data?.id || '',
    });

    const number = ref(0);
    const fileList = ref<{url?: string}[]>([]);
    const uploadList = ref<{name: string, url: string}[]>([])
    const fileUpload = ref();
    const showProcess = ref(false);
    const processPercent = ref(0);
    const processStatus = ref('');
    // 上传前校检格式和大小
    const handleBeforeUpload = (file: File) => {
        // 校检文件类型
        if (props.fileType.length) {
            const fileName = file.name.split('.');
            const fileExt = fileName[fileName.length - 1];
            const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
            if (!isTypeOk) {
                useMessage().error(`${t('excel.typeErrorText')} ${props.fileType.join('/')}!`);
                return false;
            }
        }
        // 校检文件大小
        if (props.fileSize && props.fileSize > 0) {
            const isLt = file.size / 1024 / 1024 < props.fileSize;
            if (!isLt) {
                useMessage().error(`${t('excel.sizeErrorText')} ${props.fileSize} MB!`);
                return false;
            }
        }
        number.value++;
        return true;
    };
    // 上传成功回调
    function handleUploadSuccess(res: any, file: any) {
        if (res.code === 0) {
            uploadList.value.push({ name: file.name, url: res.data.url });
            uploadedSuccessfully();
        } else {
            number.value--;
            useMessage().error(res.msg);
            fileUpload.value.handleRemove(file);
            uploadedSuccessfully();
        }
    }
    // 上传结束处理
    const uploadedSuccessfully = () => {
    	if (number.value > 0 && uploadList.value.length === number.value) {
    		fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
    		uploadList.value = [];
    		number.value = 0;
    		emit('change', listToString(fileList.value));
    		emit('update:modelValue', listToString(fileList.value));
    	}
    };
    //移除文件
    const handleRemove = (file: {url:string}) => {
        fileList.value = fileList.value.filter(f=> f.url !== file.url);
        emit('change', listToString(fileList.value));
        emit('update:modelValue', listToString(fileList.value));
    };
    //上传失败
    const handleUploadError = () => {
        useMessage().error('上传文件失败');
    };
    //上传进度
    const handleProgress = (event: any, file: any) => {
        showProcess.value = true;
        processPercent.value =Math.floor((event.loaded / event.total) * 100);
        if (processPercent.percent === 100) {
            processStatus.value = 'success';
            setTimeout(() => {
                showProcess.value = false;
            }, 1000);
        }
    };

    /**
     * 将对象数组转为字符串，以逗号分隔。
     * @param list 待转换的对象数组。
     * @param separator 分隔符，默认为逗号。
     * @returns {string} 返回转换后的字符串。
     */
    const listToString = (list: { url: string }[], separator = ','): string => {
    	let strs = '';
    	separator = separator || ',';
    	for (let i in list) {
    		if (list[i].url) {
    			strs += list[i].url + separator;
    		}
    	}
    	return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    };
</script>
